package com.example.musicplayer

import android.content.Intent
import android.os.Bundle
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.musicplayer.login.LoginActivity
import com.example.musicplayer.profile.message.MessagesFragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity() {
    private lateinit var navView: BottomNavigationView
    private lateinit var fullscreenContainer: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (!isUserLoggedIn()) {
            val intent = Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
            return
        }

        navView = findViewById(R.id.bottom_navigation)
        fullscreenContainer = findViewById(R.id.fullscreen_container)

        val findFragment = FindFragment()
        val musicFragment = MusicFragment()
        val profileFragment = ProfileFragment()

        setCurrentFragment(musicFragment)

        navView.setOnNavigationItemSelectedListener { item ->
            when (item.itemId) {
                R.id.navigation_find -> setCurrentFragment(findFragment)
                R.id.navigation_music -> setCurrentFragment(musicFragment)
                R.id.navigation_profile -> setCurrentFragment(profileFragment)
            }
            true
        }
    }

    private fun isUserLoggedIn(): Boolean {
        val sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE)
        return sharedPreferences.getBoolean("isLoggedIn", false)
    }

    private fun setCurrentFragment(fragment: Fragment) =
        supportFragmentManager.beginTransaction().apply {
            replace(R.id.fragment_container, fragment)
            addToBackStack(null) // 将事务添加到返回栈
            commit()
        }

    fun showMessagesFullscreen() {
        val messagesFragment = MessagesFragment()
        setCurrentFragment(messagesFragment)
    }

    fun hideMessagesFullscreen() {
        supportFragmentManager.popBackStack()
    }
}